package tv.scolopender.receiver;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import tv.scolopender.R;
import tv.scolopender.activity.SplashActivity;
import tv.scolopender.json.ScoloJSON;
import tv.scolopender.model.Scolo;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;

public class PollingAlarm extends BroadcastReceiver {
	int amountScolos;

	@Override
	public void onReceive(Context context, Intent intent) {
		PowerManager pm = (PowerManager) context
				.getSystemService(Context.POWER_SERVICE);
		PowerManager.WakeLock wl = pm.newWakeLock(
				PowerManager.PARTIAL_WAKE_LOCK, "");
		wl.acquire();
		Scolo scolo = null;
		try {
			scolo = new ReadNewest().execute().get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (scolo != null) {
			if (getLatestScoloId(context) == 0) {
				saveLatestScoloId(context, scolo.getId());
			}
			if (scolo.getId() > getLatestScoloId(context)) {
				NotificationManager notificationManager = (NotificationManager) context
						.getSystemService(Context.NOTIFICATION_SERVICE);
				NotificationCompat.Builder builder = new NotificationCompat.Builder(
						context);
				Intent notificationIntent = new Intent(context,
						SplashActivity.class);
				PendingIntent contentIntent = PendingIntent.getActivity(
						context, 0, notificationIntent,
						PendingIntent.FLAG_CANCEL_CURRENT);

				builder.setContentTitle("Neue Scolos sind da!")
						.setContentText(scolo.getText())
						.setSmallIcon(R.drawable.ic_launcher)
						.setNumber(scolo.getId() - getLatestScoloId(context))
						.setContentIntent(contentIntent);
				Notification noti = builder.build();

				noti.ledARGB = Color.argb(0, 255, 127, 0);
				noti.flags |= Notification.FLAG_SHOW_LIGHTS;
				noti.ledOnMS = 500;
				noti.ledOffMS = 2000;

				notificationManager.notify(1337, noti);

				// latest scolo id speichern
				SharedPreferences settings = context.getSharedPreferences(
						"ScoloPrefs", Context.MODE_PRIVATE);
				SharedPreferences.Editor editor = settings.edit();
				editor.putInt("lastScoloId", scolo.getId());
				editor.commit();

				vibrate(context);
			}
		}
		// Toast.makeText(context, "Bin da wer noch?",
		// Toast.LENGTH_SHORT).show();
		wl.release();
	}

	public void setAlarm(Context context) {
		AlarmManager am = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent i = new Intent(context, PollingAlarm.class);
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
		am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
				1000 * 60 * 60 * 2 /* ms * sec * min * h */, pi);
	}

	public void cancelAlarm(Context context) {
		Intent i = new Intent(context, PollingAlarm.class);
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
		AlarmManager am = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		am.cancel(pi);
	}

	private class ReadNewest extends AsyncTask<Integer, Void, Scolo> {

		@Override
		protected Scolo doInBackground(Integer... params) {
			ArrayList<Scolo> scolos = ScoloJSON.selectNewest(0, 1);
			if (scolos.size() > 0)
				return scolos.get(0);
			return null;
		}
	}

	private int getLatestScoloId(Context context) {
		SharedPreferences settings = context.getSharedPreferences("ScoloPrefs",
				Context.MODE_PRIVATE);
		int lastScoloId = settings.getInt("lastScoloId", 0);
		return lastScoloId;
	}

	private void saveLatestScoloId(Context context, int sid) {
		SharedPreferences settings = context.getSharedPreferences("ScoloPrefs",
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("lastScoloId", sid);
		editor.commit();
	}

	private void vibrate(Context context) {
		Vibrator v = (Vibrator) context
				.getSystemService(Context.VIBRATOR_SERVICE);

		int dot = 300; // Length of a Morse Code "dot" in milliseconds
		int gap = 500; // Length of Gap Between Letters
		long[] pattern = { 0, // Start immediately
				dot, gap, dot, gap, dot };

		v.vibrate(pattern, -1);
	}

}
